//
//  HEOneCategViewController.m
//  HealthFamily
//
//  Created by 吴欧 on 2020/10/29.
//  Copyright © 2020 honglutec. All rights reserved.
//

#import "HEOneCategViewController.h"
#import "HECategModel.h"
#import "LeftTableViewCell.h"
#import "HECategGoodsCell.h"
#import "TableViewHeaderView.h"
#import "HEGoodsDetailsViewController.h"

//static NSString *const kCellIdentifier_Left = @"LeftTableViewCell";
//static NSString *const kCellIdentifier_Right = @"HECategGoodsCell";

@interface HEOneCategViewController ()<UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, strong) UITableView *leftTableView;
@property (nonatomic, strong) UITableView *rightTableView;



@property(nonatomic, strong) NSMutableArray <HECategModel *> *dataSourceArr;

@property(nonatomic, assign) NSInteger selectIndex;
@property(nonatomic, assign) BOOL isScrollDown;

@end

@implementation HEOneCategViewController

- (NSMutableArray<HECategModel *> *)dataSourceArr {
    if (!_dataSourceArr) {
        _dataSourceArr = [NSMutableArray array];
    }
    return _dataSourceArr;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    _selectIndex = 0;
    _isScrollDown = YES;
    [self.view addSubview:self.leftTableView];
    [self.view addSubview:self.rightTableView];


    [self loadData];
}

- (UITableView *)leftTableView
{
    if (!_leftTableView)
    {
        _leftTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, ZXNavBarHeight, 120, KScreenHeight - ZXNavBarHeight)];
        _leftTableView.delegate = self;
        _leftTableView.dataSource = self;
        _leftTableView.tableFooterView = [UIView new];
        _leftTableView.showsVerticalScrollIndicator = NO;
        _leftTableView.separatorColor = KHexColor(@"EEEEEE");
        _leftTableView.backgroundColor = KHexColor(@"F7F7F7");
        [_leftTableView registerClass:[LeftTableViewCell class] forCellReuseIdentifier:kCellIdentifier_Left];
    }
    return _leftTableView;
}

- (UITableView *)rightTableView
{
    if (!_rightTableView)
    {
        _rightTableView = [[UITableView alloc] initWithFrame:CGRectMake(120, ZXNavBarHeight, SCREEN_WIDTH - 120,  KScreenHeight - ZXNavBarHeight)];
        _rightTableView.delegate = self;
        _rightTableView.dataSource = self;
        _rightTableView.showsVerticalScrollIndicator = NO;
        _rightTableView.tableFooterView = [UIView new];
        _rightTableView.separatorColor = KHexColor(@"EEEEEE");
        [_rightTableView registerClass:[HECategGoodsCell class] forCellReuseIdentifier:kCellIdentifier_Right];
    }
    return _rightTableView;
}

#pragma mark - loadData
- (void)loadData {
//    KgetGoodsByOneCategId
    
    [WOAFNetWorkingHandle GETWithBaseUrl:KServerUrl suffixUrl:KgetGoodsByOneCategId parameters:@{@"id": [NSNumber numberWithInteger:_categID]} success:^(id  _Nonnull responseObject) {

        HEArrayResponse *response = [HEArrayResponse mj_objectWithKeyValues:responseObject];
        [self dealData: [HECategModel mj_objectArrayWithKeyValuesArray:response.data]];
        
    } failure:^(NSError * _Nonnull error) {
        
    }];
}

- (void)dealData:(NSMutableArray *)arr {
    
    for (HECategModel *model in arr) {
        if (model.goodsList.count > 0) {
            [self.dataSourceArr addObject:model];
        }
    }
    

    [self.leftTableView reloadData];
    [self.rightTableView reloadData];
    
    if (self.dataSourceArr.count > 0) {
        [self.leftTableView selectRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] animated:YES scrollPosition:UITableViewScrollPositionTop];
    }
}

#pragma mark - TableView DataSource Delegate

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    if (_leftTableView == tableView) {
        return 1;
    } else {
        return self.dataSourceArr.count;
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (_leftTableView == tableView) {
        return self.dataSourceArr.count;
    } else {
        if ( self.dataSourceArr > 0) {
            HECategModel *model = self.dataSourceArr[section];
            return model.goodsList.count;
        }
        return 0;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (_leftTableView == tableView) {
        LeftTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kCellIdentifier_Left forIndexPath:indexPath];
        HECategModel *model = self.dataSourceArr[indexPath.row];
        cell.name.text = model.name;
        return cell;
    } else {
        HECategGoodsCell *cell = [tableView dequeueReusableCellWithIdentifier:kCellIdentifier_Right forIndexPath:indexPath];
        HECategModel *model = self.dataSourceArr[indexPath.section];
        HEGoodsModel *goodsModel = model.goodsList[indexPath.row];
        cell.model = goodsModel;
        return cell;
    }
}


#pragma mark -
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
     if (_rightTableView == tableView) {
        return [tableView fd_heightForCellWithIdentifier: kCellIdentifier_Right cacheByIndexPath:indexPath configuration:^(HECategGoodsCell *cell) {
            HECategModel *model = self.dataSourceArr[indexPath.section];
            HEGoodsModel *goodsModel = model.goodsList[indexPath.row];
            cell.model = goodsModel;
          }];
     }
    return [tableView fd_heightForCellWithIdentifier: kCellIdentifier_Left cacheByIndexPath:indexPath configuration:^(LeftTableViewCell *cell) {
           HECategModel *model = self.dataSourceArr[indexPath.row];
           cell.name.text = model.name;
    }];
}


- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (_rightTableView == tableView) {
        return 40;
    }
    return 0;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    if (_rightTableView == tableView) {
        TableViewHeaderView *view = [[TableViewHeaderView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 45)];
        HECategModel *model = self.dataSourceArr[section];
        view.name.text = model.name;
        return view;
    }
    return nil;
}

// TableView分区标题即将展示
- (void)tableView:(UITableView *)tableView willDisplayHeaderView:(nonnull UIView *)view forSection:(NSInteger)section
{
    // 当前的tableView是RightTableView，RightTableView滚动的方向向上，RightTableView是用户拖拽而产生滚动的（（主要判断RightTableView用户拖拽而滚动的，还是点击LeftTableView而滚动的）
    if ((_rightTableView == tableView) && !_isScrollDown && _rightTableView.dragging)
    {
        [self selectRowAtIndexPath:section];
    }
}

// TableView分区标题展示结束
- (void)tableView:(UITableView *)tableView didEndDisplayingHeaderView:(UIView *)view forSection:(NSInteger)section
{
    // 当前的tableView是RightTableView，RightTableView滚动的方向向下，RightTableView是用户拖拽而产生滚动的（（主要判断RightTableView用户拖拽而滚动的，还是点击LeftTableView而滚动的）
    if ((_rightTableView == tableView) && _isScrollDown && _rightTableView.dragging)
    {
        [self selectRowAtIndexPath:section + 1];
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(nonnull NSIndexPath *)indexPath
{
    if (_leftTableView == tableView)
    {
        _selectIndex = indexPath.row;
        [_rightTableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:_selectIndex] atScrollPosition:UITableViewScrollPositionTop animated:YES];
    }else {
        HECategModel *model = self.dataSourceArr[indexPath.section];
        HEGoodsModel *goodsModel = model.goodsList[indexPath.row];
        HEGoodsDetailsViewController *vc = [HEGoodsDetailsViewController new];
        vc.goodsId = goodsModel.id;
        vc.barType = goodsModel.visit ? HEGoodsDetailsTabBarTypeAppointment : HEGoodsDetailsTabBarTypeOnlyBuy;
        [self.navigationController pushViewController:vc animated:YES];
    }
}

// 当拖动右边TableView的时候，处理左边TableView
- (void)selectRowAtIndexPath:(NSInteger)index
{
    if (index <= self.dataSourceArr.count-1) {
        [_leftTableView selectRowAtIndexPath:[NSIndexPath indexPathForRow:index inSection:0] animated:YES scrollPosition:UITableViewScrollPositionTop];
    }
}

#pragma mark - UISrcollViewDelegate
// 标记一下RightTableView的滚动方向，是向上还是向下
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    static CGFloat lastOffsetY = 0;

    UITableView *tableView = (UITableView *) scrollView;
    if (_rightTableView == tableView)
    {
        _isScrollDown = lastOffsetY < scrollView.contentOffset.y;
        lastOffsetY = scrollView.contentOffset.y;
    }
}

@end
